package com.qfedu.vhr.employee.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.vhr.common.MailBody;
import com.qfedu.vhr.employee.entity.Employee;
import com.qfedu.vhr.employee.entity.MailSendLog;
import com.qfedu.vhr.employee.service.IEmployeeService;
import com.qfedu.vhr.employee.service.IMailSendLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author baize
 * @date 2023/2/8
 * @site www.qfedu.com
 */
@Component
public class MailScheduled {

    @Autowired
    IMailSendLogService mailSendLogService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    IEmployeeService employeeService;

    /**
     * 每隔 5 秒，去数据库中捞一次消息
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void resendMail() {
        QueryWrapper<MailSendLog> qw = new QueryWrapper<>();
        //查找状态为0并且tryTime 小于当前时间的记录
        qw.lambda().eq(MailSendLog::getStatus, 0)
                .lt(MailSendLog::getTryTime, LocalDateTime.now());
        List<MailSendLog> list = mailSendLogService.list(qw);
        for (MailSendLog log : list) {
            Integer count = log.getCount();
            if (count > 2) {
                //说明已经重试了三次了，这条消息发送失败，不再进行重试
                log.setStatus(2);
                mailSendLogService.updateById(log);
            } else {
                //重试
                log.setCount(log.getCount()+1);
                log.setUpdateTime(LocalDateTime.now());
                mailSendLogService.updateById(log);
                MailBody mailBody = new MailBody();
                Employee emp = employeeService.getById(log.getEmpId());
                mailBody.setMail(emp.getEmail());
                mailBody.setContent("欢迎加入力麒集团");
                mailBody.setMsgId(log.getMsgId());
                rabbitTemplate.convertAndSend(log.getExchange(), log.getRouteKey(), mailBody, new CorrelationData(log.getMsgId()));
            }
        }
    }
}
